package com.bawei.property.viewmodel

import androidx.lifecycle.viewModelScope
import com.bawei.common.viewmodel.BaseViewModel
import com.bawei.property.entity.CarApplyValues
import com.bawei.property.intent.CarApplyViewIntent
import com.bawei.property.model.CarApplyRepository
import com.bawei.property.uistate.CarApplyUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * Author: Jason Zhang
 * Date: 2024/5/29
 * Desc:
 */
@HiltViewModel
class CarApplyViewModel @Inject constructor(private val repository: CarApplyRepository): BaseViewModel<CarApplyViewIntent>() {

    private val _uiState = MutableStateFlow<CarApplyUiState>(CarApplyUiState.NoneState)
    val uiState: StateFlow<CarApplyUiState> = _uiState.asStateFlow()

    override fun dispatchIntent(intent: CarApplyViewIntent) {
        when(intent){
            is CarApplyViewIntent.LoadCarApplyList -> loadCarApplyList()
        }
    }


    private fun loadCarApplyList(){
        viewModelScope.launch(Dispatchers.IO) {
            try {
                var result = repository.getCarApplyList()
                if (result.statuesCode == "200"){
                    //模拟空车位数据
                    var carParkList = mutableListOf<CarApplyValues>()
                    carParkList.addAll(result.getValues())
                    //插入5条空位数据
                    for (index in 1..5){
                        carParkList.add(index, CarApplyValues().apply {
                            parkUser = 0
                            parkName = "空位"
                        })
                    }
                    _uiState.value = CarApplyUiState.LoadCarApplyListSuccess(carParkList)
                }else{
                    _uiState.value = CarApplyUiState.LoadCarApplyListFail(result.msg ?: "接口加载失败！")
                }
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                cancel()
            }
        }
    }


}